package pchi.pchicamera;

import pchi.pchicamera.models.PhotoModel;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;

public class ImagePreview {

	public static PhotoModel getImagePreview(Context context) {

		PhotoModel result = new PhotoModel();

		String[] projection = new String[] { MediaStore.Images.Media._ID,
				MediaStore.Images.Media.DATA,
				MediaStore.Images.Media.DISPLAY_NAME,
				MediaStore.Images.Media.DATE_ADDED };

		Cursor cur = context.getContentResolver().query(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
				null, null);

		cur.moveToFirst();

		int columnIndex = 0;

		columnIndex = cur.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME);
		if (columnIndex != -1) {
			result.setTitle(cur.getString(columnIndex));
		}

		columnIndex = cur.getColumnIndex(MediaStore.Images.Media.DATA);
		if (columnIndex != -1) {
			result.setPath(cur.getString(columnIndex));
		}

		columnIndex = cur.getColumnIndex(MediaStore.Images.Media._ID);
		if (columnIndex != -1) {
			result.setId(cur.getLong(columnIndex));
		}

		columnIndex = cur.getColumnIndex(MediaStore.Images.Media.DATE_ADDED);
		if (columnIndex != -1) {
			result.setDate(cur.getLong(columnIndex));
		}

		return result;
	}

	public static String getRealPathFromURI(Uri contentUri, Context mContext) {
		String[] proj = { MediaStore.Images.Media.DATA };
		CursorLoader loader = new CursorLoader(mContext, contentUri, proj,
				null, null, null);
		Cursor cursor = loader.loadInBackground();
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
}
